package ai.people.netmon.gateway.service;

import ai.people.netmon.framework.constant.NmSystemConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.List;


@Service
public class AuthService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //从头取出jwt令牌
    public String getJwtFromHeader(ServerHttpRequest request) {
        //取出头信息
        HttpHeaders headers = request.getHeaders();

        List<String> authorizations = headers.get(NmSystemConstant.AUTH_HEADER_AUTHORIZATION);
        if (authorizations == null || authorizations.isEmpty()) {
            return null;
        }
        String authorization = authorizations.get(0);
        if (!authorization.startsWith(NmSystemConstant.AUTH_HEADER_AUTHORIZATION_PREFIX)) {
            return null;
        }
        //取到jwt令牌
        String jwt = authorization.substring(NmSystemConstant.AUTH_HEADER_AUTHORIZATION_PREFIX.length());
        return jwt;
    }

    //从cookie取出token
    //查询身份令牌
    public String getTokenFromCookie(ServerHttpRequest request) {
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> httpCookies = cookies.get(NmSystemConstant.AUTH_COOKIE_TOKEN_ID);
        if (httpCookies == null || httpCookies.isEmpty()) {
            return null;
        }
        HttpCookie httpCookie = httpCookies.get(0);
        String access_token = httpCookie.getValue();
        if (StringUtils.isEmpty(access_token)) {
            return null;
        }
        return access_token;
    }

    ////查询令牌的有效期，如果过期是-2
    //public long getExpire(String accessToken) {
    //    //key
    //    String key = CloudConstant.AUTH_PREFIX  + accessToken;
    //    Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    //    String value = stringRedisTemplate.opsForValue().get(key);
    //    return expire;
    //}

    //
    ///**
    // * 延长寿命
    // *
    // * @param access_token 访问令牌
    // */
    //public void lifeExtension(String access_token){
    //    String key = "user_token:" + access_token;
    //    stringRedisTemplate.expire(key,1200,TimeUnit.SECONDS);
    //}



    //public TokenUser getUserInfo(String token){
    //    String key = "user_token:" + token;
    //    String tokenInfo = stringRedisTemplate.opsForValue().get(key);
    //    AuthToken authToken = JSONUtils.jsonToBean(tokenInfo, AuthToken.class);
    //    TokenUser tokenUser = JSONUtils.jsonToBean(authToken.getUserInfo(), TokenUser.class);
    //    return tokenUser;
    //}

}
